const dbmodel  = require("../mongo/model");
const bcrypt = require("../config/bcypt.js");
//用户信息处理
exports.userAssign = function(obj,res){//用户注册
  const passworld = bcrypt.bcryption(obj.psw);//bcrypt加密
  let options = {
    name:obj.name,
    password:passworld,
    account:obj.account
  }
  let user = new dbmodel.users(options);
  user.save((err,result)=>{
      if(err){
        res.send({status:500,err})
      }else{
        res.send({status:200,data:result})
      }
  })
}
exports.userLogin = function(data,res){//用户登录
  let wherestr = {
    account:data.account
  }
  let outstr = {name:1,account:1,imgurl:1,password:1}
  dbmodel.users.findOne(wherestr,outstr,(err,result)=>{
    if(err){
      res.send({status:500})
    }else{
      if(result == null){
        res.send({status:300});//用户名错误
      }else{
        let matchpsw = bcrypt.decodebcrypt(data.psw,result.password);
        if(matchpsw){
          res.send({status:200,data:result});//用户名密码正确
        }else{
          res.send({status:300});//密码错误
        }
      }
    }
  })
}
exports.userChange = function(data,res){//修改用户信息
 let updatestr = {}
 updatestr[data.type] = data.data;
 dbmodel.users.findByIdAndUpdate(data.id,updatestr,(err,result)=>{
    if(err){
      res.send({status:500,err})
    }else{
      res.send({status:200,data:result})
    }
  })
}


//文章信息处理
//添加文章
exports.airticleAdd = function(data,res){
  let type = data.type;//设置文章类型（0文章，1为摄影，2为随记）
  let options = {};
  if(type == 1){
    options = {
      userid:data.uid,
      title:data.title,
      imgurl:data.imgurl,
      container:data.container,
      totalinfo:data.totalinfo,
      type:type,
      include:data.include,
      time:new Date()
    }
  }else if(type == 2){
    options = {
      userid:data.uid,
      title:data.title,
      imgurl:data.imgurl,
      type:type,
      time:new Date()
    }
  }else if(type == 3){
    options = {
      userid:data.uid,
      title:data.title,
      imglist:data.imglist,
      container:data.container,
      type:type,
      time:new Date()
    }
  }
  let airtilces = new dbmodel.airtilces(options);
  airtilces.save((err,result)=>{
    if(err){
      res.send({status:500,da:err})
    }else{   
      res.send({status:200,data:result})
    }
  })
}
//删除文章
exports.airticleremove = function(data,res){
  let wherestr = {
    userid:data.uid,
    _id:data._id
  }
  dbmodel.airtilces.deleteOne(wherestr,(err,result)=>{
    if(err){
      res.send({status:500})
    }else{   
      res.send({status:200})
    }
  })
}
//删除帖子
exports.techologyremove = function(data,res){
  let wherestr = {
    userid:data.uid,
    _id:data._id
  }
  dbmodel.techologys.deleteOne(wherestr,(err,result)=>{
    if(err){
      res.send({status:500})
    }else{   
      res.send({status:200})
    }
  })
}

//修改文章信息(隐藏和点赞数)
exports.airticleInfoChange = function(data,res){
  let wherestr = {_id:data.id};
  let updatestr = {};
  if(data.type == "goods"){
    updatestr = {$inc:{goods:1}}
  }else{
    updatestr[data.type] = data.data;
  }
  dbmodel.airtilces.updateOne(wherestr,updatestr,(err,result)=>{
    if(err){
        res.send({status:500,data:err})
    }else{
        res.send({status:200})
    }
  })  
}
//显示文章列表
// exports.airticleShowlist = function(data,res){(已废弃)
//   let wherestr = {$or:[{userid:data.uid,type:data.type},{userid:{$ne:data.uid},hide:data.hide,type:data.type}]}
//   dbmodel.airtilces.find(wherestr,(err,result)=>{
//     if(err){
//       res.send({status:500,data:err})
//     }else{
//       res.send({status:200,data:result})
//     }
//   })
// }
async function airticleShowlist(data,res){
  let airticle = await getairticleShowlist(data,res).then((data)=>data);
  if(airticle.type == 2 || airticle.type == 3){
    res.send({status:200,data:airticle.data})
  }else{
    let myresulr = JSON.parse(JSON.stringify(airticle.data))
    let list = myresulr.map(async (item)=>{
      let goods = await getgoods(item._id).then(data=>data);
      let mygood = await getmygood(item._id,data.uid).then(data=>data);
      item.goods = goods
      item.mygood = mygood
      return item
    })
    list = await Promise.all(list)
    // console.log(list)
    res.send({status:200,data:list})
  }
}
function getairticleShowlist(data,res){
  return new Promise((resolve,reject)=>{
    let wherestr = {$or:[{userid:data.uid,type:data.type},{userid:{$ne:data.uid},hide:data.hide,type:data.type}]}
    dbmodel.airtilces.find(wherestr,(err,result)=>{
      if(err){
        reject({status:500,data:err})
      }else{
        resolve({type:data.type,data:result})
      }
    })
  })
}

function getgoods(aid){//获取数量
  return new Promise((resolve,reject)=>{
    let wherestr = {airticleid:aid,goods:true}
    dbmodel.airticlegoods.find(wherestr,(err,result)=>{
      if(err){
        reject(0);
      }else{
        resolve(result.length);     
      }
    })
  })
}
function getmygood(aid,uid){//获取当前点赞状态
  return new Promise((resolve,reject)=>{
    let wherestr = {airticleid:aid,userid:uid}
    let outstr = {goods:1}
    dbmodel.airticlegoods.findOne(wherestr,outstr,(err,result)=>{
      if(err){
        reject(false);
      }else{
        if(result == null){
          resolve(false);
        }else{
          resolve(result.goods);
        }
       
      }
    })
  })
}
exports.airticleShowlist =  function(data,res){
  airticleShowlist(data,res)
}
//查看文章及评论
exports.airticleDetail = function(data,res){
  let wherestr = {_id:data.id}
  let updatestr = {$inc:{watches:1}}
  dbmodel.airtilces.updateOne(wherestr,updatestr,(err,result)=>{
    if(err){
        res.send({status:500,err})
    }else{
      dbmodel.airtilces.findOne(wherestr,(err,myresult)=>{
        if(err){
          res.send({status:500,err})
        }else{
          let querry = dbmodel.comments.find({})
          querry.where({airticleid:data.id})
          querry.populate('userid')
          querry.exec().then((info)=>{
            let list = info.map((item)=>{
              let option = {
                container:item.container,
                goods:item.goods,
                bads:item.bads,
                time:item.time,
                name:item.userid.name,
                imgurl:item.userid.imgurl,//查询friendID关联到users表中的imgurl数据
              }
              return option        
            }) 
            myresult.comments = list
            res.send({status:200,data:myresult})
          })
        }
      })
    }
  })  
}




//评论信息处理
//添加评论
exports.commentAdd = function(data,res){
  let options = {
    airticleid:data.aid,
    userid:data.uid,
    container:data.container,
    time:new Date()
  }
  let comments = new dbmodel.comments(options);
  comments.save((err,result)=>{
    if(err){
      res.send({status:500,data:err})
    }else{   
      res.send({status:200})
    }
  })
}
//点赞或点否
exports.commentInfoChange = function(data,res){
  let wherestr = {_id:data.cid};
  let updatestr = {};
  const type = data.type;
  if(type == 'goods'){
    updatestr = {$inc:{goods:1}}
  }else if(type == 'bads'){
    updatestr = {$inc:{bads:1}}
  }
  dbmodel.comments.updateOne(wherestr,updatestr,(err,result)=>{
    if(err){
        res.send({status:500,data:err})
    }else{
        res.send({status:200})
    }
  })  
}
//获取评论列表
// exports.commentShowlist = function(data,res){废弃
//   let querry = dbmodel.comments.find({})
//   querry.where({airticleid:data.aid})
//   querry.populate('userid')
//   querry.exec().then((info)=>{
//     let list = info.map((item)=>{
//       let option = {
//         container:item.container,
//         goods:item.goods,
//         bads:item.bads,
//         time:item.time,
//         name:item.userid.name,
//         imgurl:item.userid.imgurl,//查询friendID关联到users表中的imgurl数据
//       }
//       return option        
//     }) 
//     res.send({status:200,data:list})
//   })
// }

async function commentShowlist(data,res){
  let comment = await getcommentShowlist(data,res).then((data)=>data);
  let myresulr = JSON.parse(JSON.stringify(comment.data))
    let list = myresulr.map(async (item)=>{
      let goods = await getcommentgoods(item._id).then(data=>data);
      let mygood = await getcommentmygood(item._id,data.uid).then(data=>data);
      item.goods = goods
      item.mygood = mygood
      return item
    })
    list = await Promise.all(list)
    // console.log(list)
    res.send({status:200,data:list})
}

exports.commentShowlist  = function(data,res){
  commentShowlist(data,res)
}

function getcommentShowlist(data,res){
  return new Promise((resolve,reject)=>{
    let querry = dbmodel.comments.find({})
    querry.where({airticleid:data.aid})
    querry.populate('userid')
    querry.exec().then((info)=>{
      let list = info.map((item)=>{
        let option = {
          _id:item._id,
          container:item.container,
          goods:item.goods,
          bads:item.bads,
          time:item.time,
          name:item.userid.name,
          imgurl:item.userid.imgurl,//查询friendID关联到users表中的imgurl数据
        }
        return option        
      }) 
      resolve({status:200,data:list})
    })
  })
    
  }

function getcommentgoods(mid){//获取数量
  return new Promise((resolve,reject)=>{
    let wherestr = {commentsid:mid,goods:true}
    dbmodel.commentsgoods.find(wherestr,(err,result)=>{
      if(err){
        reject(0);
      }else{
        resolve(result.length);     
      }
    })
  })
}
function getcommentmygood(mid,uid){//获取当前点赞状态
  return new Promise((resolve,reject)=>{
    let wherestr = {commentsid:mid,userid:uid}
    let outstr = {goods:1}
    dbmodel.commentsgoods.findOne(wherestr,outstr,(err,result)=>{
      if(err){
        reject(false);
      }else{
        if(result == null){
          resolve(false);
        }else{
          resolve(result.goods);
        }
       
      }
    })
  })
}









//发表技术交流
exports.techologyAdd = function(data,res){
  let options = {
    userid:data.uid,
    title:data.title,
    container:data.container,
    totalinfo:data.totalinfo,
    type:data.type,
    time:new Date()
  }
  let techologys = new dbmodel.techologys(options);
  techologys.save((err,result)=>{
    if(err){
      res.send({status:500,da:err})
    }else{   
      res.send({status:200,data:result})
    }
  })
}
//获取帖子
// exports.techologyShowlist = function(data,res){废弃
//   let querry = dbmodel.techologys.find({})
//   querry.where({$or:[{userid:data.uid},{userid:{$ne:data.uid}}]})
//   querry.populate('userid')
//   querry.exec().then((info)=>{
//     let list = info.map((item)=>{
//       let option = {
//         _id:item._id,
//         title:item.title,
//         container:item.container,
//         goods:item.goods,
//         type:item.type,
//         watches:item.watches,
//         time:item.time,
//         name:item.userid.name,
//         imgurl:item.userid.imgurl,
//       }
//       return option        
//     }) 
//     res.send({status:200,data:list})
//   })
// }

async function techologyShowlist(data,res){
  let techology = await gettechologyShowlist(data,res).then((data)=>data);
  let myresulr = JSON.parse(JSON.stringify(techology.data))
    let list = myresulr.map(async (item)=>{
      let goods = await gettechologygoods(item._id).then(data=>data);
      let mygood = await gettechologymygood(item._id,data.uid).then(data=>data);
      item.goods = goods
      item.mygood = mygood
      return item
    })
    list = await Promise.all(list)
    // console.log(list)
    res.send({status:200,data:list})
}

exports.techologyShowlist = function(data,res){
  techologyShowlist(data,res)
}


function gettechologyShowlist(data,res){
  return new Promise((resolve,reject)=>{
    let querry = dbmodel.techologys.find({})
    querry.where({$or:[{userid:data.uid},{userid:{$ne:data.uid}}]})
    querry.populate('userid')
    querry.exec().then((info)=>{
      let list = info.map((item)=>{
        let option = {
          userid:item.userid,
          _id:item._id,
          title:item.title,
          container:item.container,
          totalinfo:item.totalinfo,
          goods:item.goods,
          type:item.type,
          watches:item.watches,
          time:item.time,
          name:item.userid.name,
          imgurl:item.userid.imgurl,
        }
        return option        
      }) 
      resolve({status:200,data:list})
    })
  })
}


function gettechologygoods(mid){//获取数量
  return new Promise((resolve,reject)=>{
    let wherestr = {techologysid:mid,goods:true}
    dbmodel.techologyoods.find(wherestr,(err,result)=>{
      if(err){
        reject(0);
      }else{
        resolve(result.length);     
      }
    })
  })
}
function gettechologymygood(mid,uid){//获取当前点赞状态
  return new Promise((resolve,reject)=>{
    let wherestr = {techologysid:mid,userid:uid}
    let outstr = {goods:1}
    dbmodel.techologyoods.findOne(wherestr,outstr,(err,result)=>{
      if(err){
        reject(false);
      }else{
        if(result == null){
          resolve(false);
        }else{
          resolve(result.goods);
        }
       
      }
    })
  })
}










//给文章点赞
exports.airticlegoodsAdd = function(data,res){
  let wherestr = {airticleid:data.aid,userid:data.uid};
  dbmodel.airticlegoods.find(wherestr,(err,result)=>{
    if(err){
      res.send({status:500})
    }else{
      if(result.length != 0){//该点赞已经存在
        let uodatestr = {goods:data.good}
        dbmodel.airticlegoods.updateOne(wherestr,uodatestr,(err,result1)=>{
          if(err){
            res.send({status:500})
          }else{
            res.send({status:200})
          }
        })
      }else{
        let options = {
          airticleid:data.aid,
          userid:data.uid,
          goods:data.good
        }
        let airticlegoods = new dbmodel.airticlegoods(options);
        airticlegoods.save((err,result)=>{
          if(err){
            res.send({status:500})
          }else{   
            res.send({status:200})
          }
        })
      }

    }
  })
}
//给评论点赞
exports.commentsgoodsAdd = function(data,res){
  let wherestr = {commentsid:data.aid,userid:data.uid};
  // console.log(wherestr)
  dbmodel.commentsgoods.find(wherestr,(err,result)=>{
    if(err){
      res.send({status:500})
    }else{
      if(result.length != 0){//该点赞已经存在
        let uodatestr = {goods:data.good}
        dbmodel.commentsgoods.updateOne(wherestr,uodatestr,(err,result1)=>{
          if(err){
            res.send({status:500})
          }else{
            res.send({status:200})
          }
        })
      }else{
        let options = {
          commentsid:data.aid,
          userid:data.uid,
          goods:data.good
        }
        let commentsgoods = new dbmodel.commentsgoods(options);
        commentsgoods.save((err,result)=>{
          if(err){
            res.send({status:500})
          }else{   
            res.send({status:200})
          }
        })
      }

    }
  })
}
//给发帖点赞
exports.techologysgoodsAdd = function(data,res){
  let wherestr = {techologysid:data.aid,userid:data.uid};
  // console.log(wherestr)
  dbmodel.techologyoods.find(wherestr,(err,result)=>{
    if(err){
      res.send({status:500})
    }else{
      if(result.length != 0){//该点赞已经存在
        let uodatestr = {goods:data.good}
        dbmodel.techologyoods.updateOne(wherestr,uodatestr,(err,result1)=>{
          if(err){
            res.send({status:500})
          }else{
            res.send({status:200})
          }
        })
      }else{
        let options = {
          techologysid:data.aid,
          userid:data.uid,
          goods:data.good
        }
        let techologyoods = new dbmodel.techologyoods(options);
        techologyoods.save((err,result)=>{
          if(err){
            res.send({status:500})
          }else{   
            res.send({status:200})
          }
        })
      }

    }
  })
}

exports.getindexcount = function(data,res){//获取文章，项目作品，技术交流的数量
  getallcount(data,res)
}

async function getallcount(data,res){
  let aircount = await getairticlecount(data,res).then((data)=>data);
  let techcount = await gettechologycount(data,res).then((data)=>data);
  let protcount = 1;
  let mydata = [
    {
      icon:'icon-wendang',
      name:'个人分享',
      desc:'我的个人记录,图片,心得分享项目过程',
      count:aircount
    },
     {
      icon:'icon-daima',
      name:'项目作品',
      desc:'兴趣代码爱好',
      count:protcount
    },
     {
      icon:'icon-biji',
      name:'技术交流',
      desc:'分享书写中遇到的难题以及解决方法',
      count:techcount
    }
  ]
  res.send(mydata)
}

function getairticlecount(data,res){//获取文章数量
  return new Promise((resolve,reject)=>{
    let wherestr = {};
    dbmodel.airtilces.find(wherestr,(err,result)=>{
      if(err){
        reject({status:500})
      }else{
        resolve(result.length)
      }
    })
  })
}
function gettechologycount(data,res){//获取帖子数量
  return new Promise((resolve,reject)=>{
    let wherestr = {};
    dbmodel.techologys.find(wherestr,(err,result)=>{
      if(err){
        reject({status:500})
      }else{
        resolve(result.length)
      }
    })
  })
}
//主页访问记录
exports.homepagecountAdd = function(data,res){
  let options = {
    ipaddress:data.uid,
    time:new Date()
  }
  let homepage = new dbmodel.homepagecounts(options);
  homepage.save((err,result)=>{
    if(err){
      res.send({status:500,da:err})
    }else{   
      res.send({status:200,data:result})
    }
  })
}

//获取主页访问数量
exports.homepagecountGet = function(data,res){
  homepagecountGet(data,res)
}

async function homepagecountGet(data,res){
  let totalcount = await getttotalcount(data,res).then((data)=>data);
  let percount = await getperday(data,res).then((data)=>data);
  res.send({totalcount,percount})
}

function getperday(data,res){
  return new Promise((resolve,reject)=>{
    const mystart = formatDateToString();
    const myend = formatDateToString()+" 23:59:59";
    const start = new Date(mystart);
    const end = new Date(myend);
    let wherestr = {time: {$gte: start, $lt: end}}
    dbmodel.homepagecounts.find(wherestr,(err,result)=>{
      if(err){
        reject(err)
      }else{
        resolve(result.length)
      }
    })
  })
}

function getttotalcount(data,res){
  return new Promise((resolve,reject)=>{
    let wherestr = {};
      dbmodel.homepagecounts.find(wherestr,(err,result)=>{
        if(err){
          reject(0)
        }else{
          resolve(result.length)
        }
    })
  })
}

function formatDateToString(date){
	date = new Date()
	var year = date.getFullYear();
	var month = date.getMonth()+1;
	var day = date.getDate();
	// if(month<10) month = "0"+month;
	// if(day<10) day = "0"+day;
	return `${year}-${month}-${day}`;
}